package org.example.spirngmvcdemo.controller;

import org.example.spirngmvcdemo.model.UserInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RequestMapping("/user")
@RestController
public class UserController {
    // method 用来指定请求的方式
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello";
    }

    @RequestMapping("/r1")
    public String r1(String name) {
        return "name:" + name;
    }

    // 参数上加了 @RequestParam 注解之后，默认这个参数必传(required 默认为 true)
    @RequestMapping("/r2")
    public String r2(@RequestParam("name") String name) {
        return "name:" + name;
    }

    // 参数加了 @RequestParam 之后，默认必传，可以手动设置 required 属性为 false
    @RequestMapping("/r3")
    public String r3(@RequestParam(value = "age") Integer age) {
        return "age:" + age;
    }

    // 接送对象 直接在前端传对象中的每个属性(字段)即可
    @RequestMapping("/r4")
    public String r4(UserInfo user) {
        return "user:" + user.toString();
    }

    // 参数类型为 Integer(包装类) 时，可以不传 默认为 null
    // 参数为普通类型时，必须传
    @RequestMapping("/r5")
    public String r5(Integer age) {
        return "age:" + age;
    }
    // 参数为普通类型，必须传， 加了 @RequestParam 注解 手动设置 required 为 false 依然需要传
    @RequestMapping("/r6")
    public String r6(@RequestParam(value = "age", required = false) int age) {
        return "age:" + age;
    }

    @RequestMapping("/r7")
    public String r7(String[] strs) {
        return "strs:" + Arrays.toString(strs);
    }

    @RequestMapping("/r8")
    public String r8(int[] nums) {
        return "nums:" + Arrays.toString(nums);
    }

    // List 传参加上 @RequestParam 之后，和 数组传参一样
    @RequestMapping("/r9")
    public String r9(@RequestParam(value = "list",required = false) List<String> list) {
        if(list != null) {
            return "list:" + list.toString();
        }
        return "list为空";
    }

    // 接收 json 格式的数据 使用 @RequestBody
    @RequestMapping("/r10")
    public String r10(@RequestBody UserInfo userInfo) {
        return "userInfo:" + userInfo;
    }

    // 接收路由传参 使用 @PathVariable
    @RequestMapping("/r11/{name}/{age}")
    public String r11(@PathVariable String name,@PathVariable Integer age) {
        return "name:" + name + ", age:" + age;
    }

    @RequestMapping("/r12")
    public String r12(@RequestPart MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        file.transferTo(new File("D:/tmp/" + fileName));
        return "file:" + file.getOriginalFilename();
    }

}
